using Godot;
using System;
using Godot.Collections;

public partial class MetaProgression : Node
{
	GameEvents gameEvents;//自动加载文件

	public Dictionary<string, Variant> saveData = new Dictionary<string, Variant>(){
		{"metaUpgradeCurrency",0},
		{"metaUpgrades",new Dictionary<string, Variant>()},
	};

	const String SAVE_FILE_PATH = "user://game.save";

	public struct MetaUpgrades
	{
		public int quantity;
		public MetaUpgrades()
		{
			this.quantity = 0;
		}
	}

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		gameEvents = GetNode<GameEvents>("/root/GameEvents");
		gameEvents.ExperienceVialCollected += OnExperienceVialCollected;

		// this.LoadSaveFile();

		// this.AddMetaUpgrade(GD.Load<MetaUpgrade>("res://resource/meta_upgrades/experience_gain.tres"));
		this.LoadSaveFile();
		var json = Json.Stringify(saveData);
		GD.Print(json);
	}

	public void Save()
	{
		using var file = FileAccess.Open(SAVE_FILE_PATH, FileAccess.ModeFlags.Write);

		var jsonString = Json.Stringify(saveData);
		file.StoreLine(jsonString);
	}

	public void LoadSaveFile()
	{
		if (!FileAccess.FileExists(SAVE_FILE_PATH))
		{
			return;
		}
		using var saveGame = FileAccess.Open(SAVE_FILE_PATH, FileAccess.ModeFlags.Read);

		while (saveGame.GetPosition() < saveGame.GetLength())
		{
			var jsonString = saveGame.GetLine();
			var json = new Json();
			var parseResult = json.Parse(jsonString);
			if (parseResult != Error.Ok)
			{
				continue;
			}
			saveData = new Dictionary<String, Variant>((Dictionary)json.Data);
		}

	}

	public void AddMetaUpgrade(MetaUpgrade upgrade)
	{
		Dictionary<string, Variant> upgrades = saveData["metaUpgrades"].AsGodotDictionary<string, Variant>();
		if (!upgrades.ContainsKey(upgrade.id))
		{
			upgrades.Add(upgrade.id, new Dictionary{
				{"quantity",0}
			});
		}
		upgrades[upgrade.id].AsGodotDictionary()["quantity"] = (int)upgrades[upgrade.id].AsGodotDictionary()["quantity"] + 1;
		this.Save();
	}

	public int GetUpgradeCount(String upgradeId){
		if(saveData["metaUpgrades"].AsGodotDictionary<String,Variant>().ContainsKey(upgradeId)){
			return saveData["metaUpgrades"].AsGodotDictionary<String,Variant>()[upgradeId].AsGodotDictionary()["quantity"].AsInt32();
		}else{
			return 0;
		}
	}


	public void OnExperienceVialCollected(int number)
	{
		saveData["metaUpgradeCurrency"] = (int)saveData["metaUpgradeCurrency"] + number; 
	}
}
